/**
 * Created by hjqi on 2016/6/8.
 */
module.controller('ConfigFileSetOperatorNavController',
    function($scope, $rootScope,$state, $stateParams, $http,k8sService){
        $scope.editorOptions = {
            lineWrapping : true,
            lineNumbers: true,
            mode: 'xml',
            readOnly:"nocursor"
        };

        $scope.curImg = undefined;
        $scope.createEvt = {};
        $scope.myPromise = undefined;
        $scope.templateUrl = '/template/cp/ngbusytemplate.html';

        $scope.serviceController = 'ServiceCreateController';
        $scope.op = 'create';

        $scope.cfgSet = $stateParams.cfgSet;

        $scope.sub = {};
        $scope.sub.volumes = [];
        $scope.sub.portInfos = [];
        $scope.sub.envInfos = [];
        $scope.sub.version = "";

        var _deregistry_upd_svc_st = undefined;

        $scope.modal = {};
        $scope.modal.steps = [
            {num:1,title:'选择镜像'},
            {num:2,title:'创建配置组'},
            {num:3,title:'创建变量组'}
        ];
        $scope.modal.step = 0;

        $scope.autoScalerEntity = {max: 5};

        $scope.isFirstStep = function () {
            return $scope.modal.step === 0;
        };

        $scope.isLastStep = function () {
            return $scope.modal.step === ($scope.modal.steps.length - 1);
        };

        $scope.isCurrentStep = function (step) {
            return $scope.modal.step === step;
        };

        $scope.setCurrentStep = function (step) {
            if(!$scope.lockStep)
                $scope.modal.step = step;
        };

        $scope.getCurrentStep = function () {
            return $scope.modal.steps[$scope.modal.step].num;
        };

        $scope.getNextLabel = function () {
            var _lastLabel = '添加';
            if($scope.op === 'update' && $scope.cfs.verList !== undefined){
                _lastLabel = '更新';
                return _lastLabel;
            }
            return ($scope.isLastStep()) ? _lastLabel : '下一步';
        };

        $scope.handlePrevious = function () {
            if(!$scope.lockStep){
                if($scope.isFirstStep())
                    $state.go('cp.configFileSetList');
                else
                    $scope.modal.step -= 1;
            }else if($scope.op === 'update'){
                $state.go('cp.configFileSetList');
            }
        };

        $scope.handleNext = function () {
            if ($scope.isLastStep()) {

                if($scope.sub.version === ""){
                    alertify.error('no version to create');
                }else
                    $scope.$broadcast('submit');
                  //  alertify.error('need to wait previous operator finished');

            } else {

                if($scope.op === 'update'){
                    if($scope.sub.version !== undefined && $scope.sub.version !== ""  ){
                        $scope.$broadcast('submit');
                    }else if($scope.sub.version === ""){
                        alertify.error('no version to update');
                    }

                }else{
                    //下一步 or 添加、更新
                    $scope.modal.step += 1;
                    $scope.currtab =  $stateParams.currtab ;
                    // console.log( "currtab--->"+$stateParams.currtab) ;
                    //当前已经是最后一步更新了
                }

            }
        };
        var updateEditorHeight=function () {
            if(jQuery("div.filelist").clientHeight>jQuery("div.editarea").clientHeight){

            }
        }
        var selectImage=function(name){
            return new Promise(function(resolve){
                $http({
                    url:'/appConfig/listConfigFileSet?image='+name,
                    method:'GET'
                }).success(function(data,header,config,status){
                    //响应成功
                    $scope.configFileSets=data;
                    if(data.length>0)
                        $scope.FromVersion=data[0];
                    resolve(true);
                    //console.log(JSON.stringify(data));
                }).error(function(data,header,config,status){
                });
            });
        };


        $scope.selectImg = function(item){
            $scope.curImg = item;
            $scope.files=[];
            selectImage(item.name).then(function () {
                $scope.handleNext();
            });
        }
        $scope.copyVersion=function(files){

            if(files !== undefined){
                files.forEach(function(file){
                    if($scope.files.indexOf(file) === -1)
                        $scope.files.push(file);
                })
                //$scope.files=$scope.files.concat(files);
                updateEditorHeight();
            }
        }
        var updateDisplay=function(value){
            $scope.currentFile.value=value;
        }
        var updateDisplayUsingServerFile=function (file) {
            delete file.value;
            if(!file.hasOwnProperty("version")){
                updateDisplay("");
                return;
            }
            $http({
                url:'/appConfig/getConfigFile',
                method:'POST',
                data:{
                    "filepath": file.filepath,
                    "imageName": $scope.curImg.name,
                    "version":file.version
                }
            }).success(function(data,header,config,status){
                if($scope.currentFile !== undefined && $scope.currentFile.filepath === file.filepath){
                    updateDisplay(data.value);
                    $scope.currentFile.originValue=data.value;
                }
            }).error(function(data,header,config,status){
            });
        }

        $scope.editFile=function(file){
            $scope.currentFile=file;
            setEditContent();
            if(file.hasOwnProperty("value")) {
                updateDisplay(file.value);
                return;
            }
            updateDisplayUsingServerFile(file);
        }
        $scope.deleteFile=function(file){
            for(var index in $scope.files) {
                if($scope.files[index]==file)
                    $scope.files.splice(index,1);
            }
        }
        $scope.resetFile=function(file) {
            updateDisplayUsingServerFile(file);
            // console.log($scope.files);
        }
        if ($stateParams.cfs) {
            $scope.cfs=$stateParams.cfs;
            $scope.op = 'update';
            //$scope.sub.version = $scope.cfs.verItem.imgVersion;
            $scope.curImg = {
                imageshortname:$scope.cfs.imageName,
                name:$scope.cfs.imageName,
                isMarket:$scope.cfs.isMarket
            }
            $scope.files=[];
            $scope.modal.steps[1].title = '更新配置组';
            //set crate form page
            /*selectImage($scope.cfs.imageName).then(function () {
                for(var index in $scope.configFileSets) {
                    if($scope.configFileSets[index].imageVersion==$scope.cfs.imageVersion)
                        $scope.copyVersion($scope.configFileSets[index]);
                }
                $scope.setCurrentStep(1);
                //lock the page and not allow to switch
                $scope.lockStep = true;

                console.log($stateParams.cfs);
            });*/

            //getCfgfile($scope.cfs.files).then(function(ret){

                //添加版本case
                if($scope.cfs.verItem)
                    $scope.copyVersion($scope.cfs.verItem.files);
                $scope.setCurrentStep(1);
                //lock the page and not allow to switch
                $scope.lockStep = true;
            //});

        }
        var initService = function() {
            //deploy through image market
            if (selectedImage || updatingService) {

                //trigger load images service
                if (selectedImage)
                    $scope.curImg = selectedImage;
                else if (updatingService) {
                    $scope.volumeType= updatingService.dbJson.volumeType ; //assign the volume type of pod e.g:glusterfs ,hostPath
                    $scope.op = 'update';
                    $scope.modal.steps[1].title = '更新服务';
                    $scope.updatingService = updatingService;
                }
                //set crate form page
                $scope.setCurrentStep(1);
                //lock the page and not allow to switch
                $scope.lockStep = true;
                //add class create_table_ul
                $scope.tabcls = 'create_table_ul';
                $scope.licls = 'create_table_li';

            }
        }

        function setEditContent(){
            $scope.editorOptions.readOnly = false;
        }

        var selectedImage = null;
        if ($stateParams.imageName && $stateParams.isMarket) {
            selectedImage = {
                name: $stateParams.imageName,
                isMarket: $stateParams.isMarket
            }
            initService();
        } else {
            var updatingService = null;
            if ($stateParams.service) {
                // console.log('/cp/service/update/gee:volumeType='+ JSON.stringify( $stateParams.service.dbJson.volumeType ) ) ;
                updatingService = $stateParams.service;
                initService();
            } else if ($stateParams.serviceName) {
                var serviceName = $stateParams.serviceName;
                k8sService.getServices(serviceName).then(function (result) {
                    if (result.data.length === 0)
                        alertify.alert('服务不存在', serviceName);
                    else {
                        updatingService = result.data[0];
                        //查询伸缩组件
                        initService();
                    }
                }, function (err) {
                    alertify.alert('query applications err', ret.data);
                });
            }
        }

        $scope.$watch('createEvt',function(_new,_old){
            if(_new !== undefined){
                $scope.myPromise = _new.promise;
            }
        },true);

        _deregistry_upd_svc_st = $rootScope.$on('updateServiceStatus',function(event,service){
            if($scope.updatingService !==undefined && $scope.updatingService.app === service.app){
                $scope.updatingService.dbJson.totalStatue = service.totalStatue;
                $scope.updatingService.totalStatue = service.totalStatue;
            }
        });

        function isServiceInMidStatus(service){
            return  ( service.totalStatue === "starting" || service.totalStatue === "restarting" || service.totalStatue === "stoping");
        }

        $scope.$on('$destroy', function(){

            //unsubscribe event
            if(_deregistry_upd_svc_st !== undefined)
                _deregistry_upd_svc_st();

        });
});